package com.n9.qqonline.sales.view;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ice
 * @since 2019/3/18 15:42
 */
public class FreemarkerUtils {

    private static Map<String, Template> templates = new ConcurrentHashMap<>();

    /**
     * 渲染ft模板
     * @param ftlName
     * @param model
     * @return
     */
    public static String render(String ftlName, Object model) {
        if (Objects.isNull(ftlName) || ftlName.length() == 0) {
            return null;
        }

        try {
            Template template = templates.get(ftlName);
            if (Objects.isNull(template)) {
                Configuration config = new Configuration(Configuration.getVersion());
                config.setClassForTemplateLoading(FreemarkerUtils.class, "/ftl");
                config.setDefaultEncoding("UTF-8");
                template = config.getTemplate(ftlName);
                templates.put(ftlName, template);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            template.process(model, new BufferedWriter(new OutputStreamWriter(out)));
            return new String(out.toByteArray(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
